package com.ruoyi.system.controller.standard;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@RequestMapping("/sse")
public class SSEController {

    private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();


    @GetMapping("/subscribe")
    public SseEmitter subscribe() {
        SseEmitter emitter = new SseEmitter(30*60*1000L);  // 设置超时时间为 30 分钟
        emitters.add(emitter);

        System.out.println("客户端已订阅, 当前连接数量: " + emitters.size());

        emitter.onCompletion(() -> {
            emitters.remove(emitter);
            System.out.println("当前任务完成, 当前连接数量: " + emitters.size());
        });

        emitter.onTimeout(() -> {
            emitters.remove(emitter);
            System.out.println("连接超时, 当前连接数量: " + emitters.size());
        });

        emitter.onError((throwable) -> {
            emitters.remove(emitter);
            System.out.println("连接发生错误, 当前连接数量: " + emitters.size());
        });

        return emitter;
    }

    public void sendMessage(String message) {

        System.out.println("当前连接数量:" + emitters.size());  // 输出当前 emitters 的数量

        for (SseEmitter emitter : emitters) {
            try {
                System.out.println("消息内容: " + message);
                emitter.send(message, MediaType.TEXT_PLAIN);
                System.out.println("消息成功发送到连接: " + emitter);
            } catch (Exception e) {
                emitter.completeWithError(e);
                emitters.remove(emitter);  // 如果发送失败，移除失效的连接
                System.err.println("发送消息失败, 连接: " + emitter);
                System.err.println("当前连接数量:" + emitters.size());
            }
        }
    }
}
